/**
 *   ro.dandanciu.webgallery.util.email.framework.EmailFromTemplate.java [WebGalleryUtil]
 *   Copyright (C) Jul 19, 2008 - Dan Danciu
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 59 Temple Place - Suite 330,
 *   Boston, MA 02111-1307, USA.
 */
package ro.dandanciu.webgallery.util.email.framework;

import java.util.List;
import java.util.Locale;
import java.util.Map;

import org.springframework.context.support.ReloadableResourceBundleMessageSource;

import ro.dandanciu.webgallery.util.email.EmailMessage;
import ro.dandanciu.webgallery.util.email.EmailSender;
import ro.dandanciu.webgallery.util.email.framework.exceptions.NoSuchEmailTemplateException;

/**
 * Email Message generated from a template
 *
 * @author Dan Danciu
 */
public class EmailFromTemplate extends EmailMessage {

    private static final String TEMPLATES_FILES = "email.templates";

    private static final String SUBJECT_SUFFIX = ".subject";

    private static final String BODY_SUFFIX = ".body";

    private static final ReloadableResourceBundleMessageSource ms;

    static {
        ms = new ReloadableResourceBundleMessageSource();
        ms.setBasename("email");
        ms.setFallbackToSystemLocale(true);
    }

    public EmailFromTemplate(final String key, final Locale locale,
            final Map<String, String> params) throws NoSuchEmailTemplateException {

        setSubject(replaceParams(ms.getMessage(key + SUBJECT_SUFFIX, null, locale), params));
        setBody(replaceParams(ms.getMessage(key + BODY_SUFFIX, null, locale), params));
    }

    private String replaceParams(final String message, final Map<String, String> params) {
        String newMessage = message;
        for (final String key : params.keySet()) {
            newMessage = newMessage.replaceAll("\\{\\{" + key + "\\}\\}", params.get(key));
        }
        return newMessage;
    }

    public void send(final List<String> toAddresses) {
        this.setToAddresses(toAddresses);
        EmailSender.send(this);
    }

}
